package com.example.taobaounion.ui.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;
import com.example.taobaounion.model.bean.HomePagerContent;
import com.example.taobaounion.model.bean.IBaseInfo;
import com.example.taobaounion.utils.UrlUtils;

import java.util.ArrayList;
import java.util.List;
//轮播图适配器
public class LooperPagerAdapter extends PagerAdapter {
    List<HomePagerContent.DataBean> mData=new ArrayList<>();
    private OnLooperPageItemClickListener mItemClickListener=null;

    @Override
    public Object instantiateItem(@NonNull  ViewGroup container, int position) {
        //因为你下面返回的size已经改为Integer.MAX_VALUE而你的position只有0,1,2,3,4,当position是5会报越界的错
        //处理一下越界的问题
        //size=5   0,1,2,3,4
        //0--0
        //1--1
        //2--2
        //3--3
        //4--4
        //5--0
        //6--1
        int realPosition=position%mData.size();
        HomePagerContent.DataBean dataBean = mData.get(realPosition);
        String coverPath = UrlUtils.getCoverPath(dataBean.getPict_url());
        //要获取图片的size的话因为添加到container，所以只需要container的高度和宽度即可
        int measuredHeight = container.getMeasuredHeight();
        int measuredWidth = container.getMeasuredWidth();
        ImageView iv = new ImageView(container.getContext());
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        iv.setLayoutParams(layoutParams);
        iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Glide.with(container.getContext()).load(coverPath).into(iv);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mItemClickListener != null) {
                    mItemClickListener.onLooperItemClick(mData.get(realPosition));
                }
            }
        });
        container.addView(iv);
        return iv;
    }

    @Override
    public void destroyItem(@NonNull  ViewGroup container, int position, @NonNull  Object object) {
        container.removeView((View) object);
    }
    public int getDataSize(){
        return mData.size();
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    //判断是否相同
    @Override
    public boolean isViewFromObject(@NonNull  View view, @NonNull Object object) {
        return view==object;
    }

    public void setData(List<HomePagerContent.DataBean> contents) {
      mData.clear();
      mData.addAll(contents);
      notifyDataSetChanged();

    }
    public interface OnLooperPageItemClickListener {
        void onLooperItemClick(IBaseInfo item);
    }
    public void setOnLooperPageItemClickListener(OnLooperPageItemClickListener listener){
        this.mItemClickListener=listener;
    }
}
